package com.yonyou.crm.sact.schedule.appctrl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.base.AppBaseCtrl;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.rest.constant.AppCodeConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.cum.contact.entity.ContactVO;
import com.yonyou.crm.cum.customer.appctrl.AppCustomerCtrl;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.sact.outwork.entity.TraceVO;
import com.yonyou.crm.sact.schedule.entity.ScheduleCommentVO;
import com.yonyou.crm.sact.schedule.entity.ScheduleGoodjobVO;
import com.yonyou.crm.sact.schedule.entity.ScheduleStatusEnum;
import com.yonyou.crm.sact.schedule.entity.ScheduleTypeEnum;
import com.yonyou.crm.sact.schedule.entity.ScheduleVO;
import com.yonyou.crm.sact.schedule.rmitf.IScheduleRmService;
import com.yonyou.crm.sact.taskcard.entity.PresetTaskcardEnum;
import com.yonyou.crm.sact.visit.entity.VisitsVO;
import com.yonyou.crm.sact.visit.rmitf.IVisitsRmService;
import com.yonyou.crm.sact.visitrule.entity.VisitruleTaskcardVO;
import com.yonyou.crm.sact.visitrule.entity.VisitruleVO;
import com.yonyou.crm.sys.modules.entity.BiztypeEnum;
import com.yonyou.crm.sys.modules.entity.MtObjTypeEnum;
import com.yonyou.iuap.context.InvocationInfoProxy;

@RestController
@RequestMapping(value = "/{version}/msact/schedules")
public class AppScheduleCtrl extends AppBaseCtrl {
	
	@Autowired
	private IScheduleRmService service;
	
	@Autowired
	private IVisitsRmService visitService;
	
	/**
	 * 查询拜访计划
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object getlist(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		Map<String, Object> searchMap = new HashMap<String, Object>();
		
		String dateStr = paramObj.getString("date");
		Date date = transformDateFromStr(dateStr, "yyyy-MM-dd");
		searchMap.put("date", date) ;
		
		List<String> filter = JSONArray.toList(JSONArray.fromObject(paramObj.get("filter")), new String(), new JsonConfig());
		if (filter != null) {
			searchMap.put("filter", filter) ;
		}

		List<ScheduleVO>  list = service.getScheduleList(searchMap);
		
		Map<String, Object> res = new HashMap<String, Object>();
		long totalNum = list.size();
		res.put("totalnum", totalNum);
		List<Map<String, Object>> scheduleList = new ArrayList<Map<String, Object>>();
		Map<String, Long> numMap = new HashMap<>();
		numMap.put("completeNum", (long)0);
		numMap.put("inHandNum", (long)0);
		numMap.put("uncompleteNum", (long)0);
		
		for(int i = 0 ; i < totalNum; i++) {
			ScheduleVO visit = list.get(i);
			Map<String, Object> schedule = new HashMap<String, Object>();
			getScheduleStatus(visit, schedule, numMap);
			schedule.put("id", visit.getId());
			CustomerVO cum = visit.getCumInfo();
			getCustomerInfo(cum,schedule); //设置客户信息
			schedule.put("objtype", visit.getType());
			schedule.put("owner", visit.getOwnerInfo().getName());
			schedule.put("ownerdept", visit.getOwnerInfo().getDeptName());
			getTaskCardList(visit, schedule); //设置任务卡信息
			scheduleList.add(schedule);
		}
		
		res.put("schedulelist", scheduleList);
		res.put("uncompletenum", numMap.get("uncompleteNum"));
		res.put("completenum", numMap.get("completeNum"));
		res.put("inHandNum", numMap.get("inHandNum"));
		return ResponseUtil.getObject(res);
	}
	
	/**
	 * 日程列表状态统计
	 * @param visit
	 * @param schedule
	 * @param numMap
	 */
	private void getScheduleStatus(ScheduleVO visit, Map<String, Object> schedule, Map<String, Long> numMap) {
		String status = String.valueOf(visit.getStatus());
		long uncompleteNum = numMap.get("uncompleteNum");
		long completeNum = numMap.get("completeNum");
		long inHandNum = numMap.get("inHandNum");
		if (String.valueOf(ScheduleStatusEnum.NOT_START.getValue()).equals(status)) {
			schedule.put("status", ScheduleStatusEnum.NOT_START.getValue());
			uncompleteNum ++;
		} else if (String.valueOf(ScheduleStatusEnum.IN_HAND.getValue()).equals(status)) {
			schedule.put("status", ScheduleStatusEnum.IN_HAND.getValue());
			inHandNum ++;
		} else if (String.valueOf(ScheduleStatusEnum.COMPLETED.getValue()).equals(status)) {
			schedule.put("status", ScheduleStatusEnum.COMPLETED.getValue());
			completeNum ++;
		} else {
			//nothing
		}
		numMap.put("uncompleteNum", uncompleteNum);
		numMap.put("completeNum", completeNum);
		numMap.put("inHandNum", inHandNum);
	}
	
	/**
	 * 获取日程客户信息
	 * @param cum
	 * @param schedule
	 */
	private void getCustomerInfo(CustomerVO cum, Map<String, Object> schedule) {
		String customerName = "";
		String customerAddr = "";
		if (cum != null) {
			customerName = cum.getName();
			customerAddr = getAddressInfo(cum);
		}
		schedule.put("accountname", customerName);
		schedule.put("accountaddress", customerAddr);
	}
	
	/**
	 * 获取任务卡列表
	 * @param visit
	 * @param schedule
	 */
	private void getTaskCardList(ScheduleVO visit, Map<String, Object> schedule) {
		//TODO 任务卡
		List<Map<String, Object>> taskCards = new ArrayList<Map<String, Object>>();
		VisitruleVO visitRule = visit.getVisitRule();
		if(visitRule != null){
			List<VisitruleTaskcardVO> stList = visitRule.getTaskcardList();
			if(stList != null && stList.size() > 0){
				for(VisitruleTaskcardVO vrtc : stList){
					getTaskCardInfo(visit, vrtc, taskCards);
				}
			}
		}
		Map<String, Object> card = new HashMap<String, Object>();
		card.put("type", "Summray");
		card.put("name", "拜访小结");
		card.put("isrequired", "Y");
		card.put("subbnstype", null);
		card.put("iscollection", visit.getSummaryFlag());
		taskCards.add(card);
		schedule.put("taskcards", taskCards);
	}
	
	/**
	 * 获取任务卡信息
	 * @param visit
	 * @param vrtc
	 * @param taskCards
	 */
	private void getTaskCardInfo(ScheduleVO visit, VisitruleTaskcardVO vrtc, List<Map<String, Object>> taskCards) {
		if(vrtc.getMtObjId() != null && !vrtc.getMtObjId().equals(new Long("0"))){
			Map<String, Object> card = getTaskCard(vrtc);
			taskCards.add(card);
		}
		if(vrtc.getMtObjId() != null && vrtc.getMtObjId().equals(new Long("0"))
				&& vrtc.getTaskcardName() != null 
				&& vrtc.getTaskcardName().equals(PresetTaskcardEnum.CUS_DETAIL.getName())){
			Map<String, Object> card = getCustomerDeitailTaskCard(vrtc);
			taskCards.add(card);
		}
		if(vrtc.getMtObjId() != null && vrtc.getMtObjId().equals(new Long("0"))
				&& vrtc.getTaskcardName() != null 
				&& vrtc.getTaskcardName().equals(PresetTaskcardEnum.LOCATIONS.getName())){
			Map<String, Object> card = getLocationTaskCard(visit, vrtc);
			taskCards.add(card);
		}
	}
	
	/**
	 * 获取任务卡
	 * @param vrtc
	 * @return
	 */
	private Map<String, Object> getTaskCard(VisitruleTaskcardVO vrtc) {
		Map<String, Object> card = new HashMap<String, Object>();
		if(vrtc.getMtObjId().equals(MtObjTypeEnum.CONTACT.getValue())){
			card.put("type", MtObjTypeEnum.CONTACT.getName());
		}else if(vrtc.getMtObjId().equals(MtObjTypeEnum.LEAD.getValue())){
			card.put("type", MtObjTypeEnum.LEAD.getName());
		}else if(vrtc.getMtObjId().equals(MtObjTypeEnum.OPPORTUNITY.getValue())){
			card.put("type", MtObjTypeEnum.OPPORTUNITY.getName());
		}else if(vrtc.getMtObjId().equals(MtObjTypeEnum.COMPETITIVE.getValue())){
			card.put("type", MtObjTypeEnum.COMPETITIVE.getName());
		}
		card.put("name", vrtc.getTaskcardName());
		card.put("isrequired", vrtc.getRequired()==1?"Y":"N");
		card.put("subbnstype", vrtc.getMtBiztypeName());
		card.put("iscollection", vrtc.getWriteFlag());
		return card;
	}
	
	/**
	 * 获取客户详情任务卡
	 * @param vrtc
	 * @return
	 */
	private Map<String, Object> getCustomerDeitailTaskCard(VisitruleTaskcardVO vrtc) {
		Map<String, Object> card = new HashMap<String, Object>();
		card.put("type", "Customerdetail");
		card.put("name", vrtc.getTaskcardName());
		card.put("isrequired", vrtc.getRequired()==1?"Y":"N");
		card.put("subbnstype", null);
		card.put("iscollection", vrtc.getWriteFlag());
		return card;
	}
	
	/**
	 * 获取签到任务卡
	 * @param visit
	 * @param vrtc
	 * @return
	 */
	private Map<String, Object> getLocationTaskCard(ScheduleVO visit, VisitruleTaskcardVO vrtc) {
		Map<String, Object> card = new HashMap<String, Object>();
		card.put("type", "Trace");
		card.put("name", vrtc.getTaskcardName());
		card.put("isrequired", vrtc.getRequired()==1?"Y":"N");
		card.put("subbnstype", null);
		card.put("iscollection", visit.getTraceFlag());
		return card;
	}
	
	/**
	 * 日程日期列表
	 * @param version
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="datelist", method = RequestMethod.GET)
	public Object getDateList(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		Map<String, Object> searchMap = new HashMap<String, Object>();
		
		String startDateStr = paramObj.getString("startdate");
		Date startDate = transformDateFromStr(startDateStr, "yyyy-MM-dd");
		searchMap.put("startDate", startDate) ;
		
		String endDateStr = paramObj.getString("enddate");
		Date endDate = transformDateFromStr(endDateStr, "yyyy-MM-dd");
		searchMap.put("endDate", endDate) ;

		List<String>  dateList = service.getScheduleDateList(searchMap);
		
		Map<String, Object> res = new HashMap<String, Object>();
		res.put("datelist", dateList);
		
		return ResponseUtil.getObject(res);
	}

	/**
	 * 拜访计划详情
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ServerError, "id不能为空");
		}
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String objType = paramObj.getString("objtype");
		
		switch(objType) {
			case "CustomerVisit":
				return visitDetail(id);
			case "NetVisit":
				//TODO 网点拜访详情
				break;
			case "Task":
				//TODO 任务详情
				break;
			default:
				//nothing
		}
		
		return ResponseUtil.getObject();
	}
	
	/**
	 * 客户拜访详情
	 * @param id
	 * @return
	 * @throws CrmMessageException
	 */
	private Object visitDetail(Long id) throws CrmMessageException {
		VisitsVO visit = visitService.getDetail(id);
		
		Map<String, Object> res = new HashMap<String, Object>();
		Map<String, Object> fixItems = new HashMap<String, Object>();
		List<Map<String, Object>> unFixItems = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> taskCards = new ArrayList<Map<String, Object>>();
		List<String> actions = new ArrayList<String>();
		
		CustomerVO cumstomer = visit.getCumInfo();
		fixItems.put("accountname", cumstomer.getName());
		fixItems.put("accountid", cumstomer.getId());
		
		fixItems.put("bizoppid", visit.getOpportunityId());
		if ((visit.getOpportunityId() == null) || (visit.getOpportunityId() == 0)) {
			fixItems.put("bizoppname", "");
		} else {
			fixItems.put("bizoppname", visit.getOpportunityInfo().getName());
		}
		
		fixItems.put("purpose", visit.getPurpose());
		fixItems.put("summary", visit.getSummary());
		fixItems.put("date", formateDate(visit.getDate(), "yyyy-MM-dd"));
		fixItems.put("nextdate", formateDate(visit.getNextDate(), "yyyy-MM-dd"));
		
		getVisitContactList(visit, fixItems);
		getVisitStatus(visit, fixItems);
		getVisitSignInfo(visit, fixItems);

		res.put("fixitems", fixItems);
		res.put("unfixitems", unFixItems);
		String userId = InvocationInfoProxy.getParameter("id");
		if ((userId.equals(String.valueOf(visit.getOwnerUserId()))) && (visit.getStatus() != ScheduleStatusEnum.COMPLETED.getValue())) {
			actions.add("edit");
		}
		res.put("actions", actions);
		
		//TODO 任务卡列表和关联信息列表
		List<Map<String, Object>> taskcards = new ArrayList<Map<String,Object>>();
		getVisitTaskCardList(visit, taskcards);
		res.put("taskcards", taskcards);
		return ResponseUtil.getObject(res);
	}
	
	/**
	 *  获取客户拜访联系人列表
	 * @param visit
	 * @param fixItems
	 */
	private void getVisitContactList(VisitsVO visit, Map<String, Object> fixItems) {
		if ((visit.getContactId() == null) || (visit.getContactId().equals(""))) {
			fixItems.put("contactname", new ArrayList<String>());
			fixItems.put("contactid", new ArrayList<String>());
		} else {
			List<ContactVO> contactList = visit.getContactInfo();
			int listSize = contactList.size();
			List<String> contactIdList = new ArrayList<String>();
			List<String> contactNameList = new ArrayList<String>();
			
			if (listSize > 0) {
				for (int i = 0; i < listSize; i++) {
					ContactVO contact = contactList.get(i);
					contactIdList.add(String.valueOf(contact.getId()));
					contactNameList.add(contact.getName());
				}
			} 
			fixItems.put("contactname", contactIdList);
			fixItems.put("contactid", contactNameList);
		}
	}
	
	/**
	 * 获取客户拜访状态
	 * @param visit
	 * @param fixItems
	 */
	private void getVisitStatus(VisitsVO visit, Map<String, Object> fixItems) {
		String status = String.valueOf(visit.getStatus());
		if (String.valueOf(ScheduleStatusEnum.NOT_START.getValue()).equals(status)) {
				fixItems.put("status", ScheduleStatusEnum.NOT_START.getValue());
		} else if (String.valueOf(ScheduleStatusEnum.IN_HAND.getValue()).equals(status)) {
				fixItems.put("status", ScheduleStatusEnum.IN_HAND.getValue());
		} else if (String.valueOf(ScheduleStatusEnum.COMPLETED.getValue()).equals(status)) {
				fixItems.put("status", ScheduleStatusEnum.COMPLETED.getValue());
		} else {
			//nothing
		}
	}
	
	/**
	 * 获取客户拜访签到信息
	 * @param visit
	 * @param fixItems
	 * @throws CrmMessageException
	 */
	private void getVisitSignInfo(VisitsVO visit, Map<String, Object> fixItems) throws CrmMessageException{
		Map<String, Object> signInfo = new HashMap<String, Object>();
		if ((visit.getTraceId() == null) || (visit.getTraceId() == 0)) {
			signInfo.put("latitude", "");
			signInfo.put("longitude", "");
			signInfo.put("address", "");
			fixItems.put("signintime", "");
		} else {
			TraceVO traceVO = visit.getTraceInfo();
			signInfo.put("latitude", traceVO.getLatitude());
			signInfo.put("longitude", traceVO.getLongitude());
			signInfo.put("address", traceVO.getAddress());
			fixItems.put("signintime", formateDate(traceVO.getSignTime(), "yyyy-MM-dd HH:mm:ss"));
		}
		fixItems.put("signinfo", signInfo);
	}
	
	/**
	 * 获取客户拜访任务卡列表
	 * @param visit
	 * @param taskcards
	 */
	private void getVisitTaskCardList(VisitsVO visit, List<Map<String, Object>> taskcards) {
		//TODO 任务卡列表和关联信息列表
		VisitruleVO visitRule = visit.getVisitRule();
		List<VisitruleTaskcardVO> vrtcList = visitRule.getTaskcardList();
		if(vrtcList != null && vrtcList.size() > 0){
			for(VisitruleTaskcardVO vrtc : vrtcList){
				if(!vrtc.getMtObjId().equals(new Long("0"))){
					Map<String, Object> card = new HashMap<String, Object>();
					if(vrtc.getMtObjId().equals(MtObjTypeEnum.CONTACT.getValue())){
						card.put("type", MtObjTypeEnum.CONTACT.getName());
					}else if(vrtc.getMtObjId().equals(MtObjTypeEnum.LEAD.getValue())){
						card.put("type", MtObjTypeEnum.LEAD.getName());
					}else if(vrtc.getMtObjId().equals(MtObjTypeEnum.OPPORTUNITY.getValue())){
						card.put("type", MtObjTypeEnum.OPPORTUNITY.getName());
					}else if(vrtc.getMtObjId().equals(MtObjTypeEnum.COMPETITIVE.getValue())){
						card.put("type", MtObjTypeEnum.COMPETITIVE.getName());
					}
					card.put("name", vrtc.getTaskcardName());
					card.put("isrequired", vrtc.getRequired()==1?"Y":"N");
					card.put("subbnstype", vrtc.getMtBiztypeName());
					card.put("ishasmore", "NO");
					List<Map<String, Object>> taskValues = new ArrayList<Map<String,Object>>();
					List<Map<String, Object>> contactList = vrtc.getContactList();
					if(contactList != null && contactList.size() > 0){
						for(Map<String, Object> contact : contactList){
							Map<String, Object> taskValue = new HashMap<String, Object>();
							taskValue.put("name", contact.get("name"));
							taskValue.put("id", contact.get("id"));
							taskValues.add(taskValue);
						}
					}
					List<Map<String, Object>> leadList = vrtc.getLeadList();
					if(leadList != null && leadList.size() > 0){
						for(Map<String, Object> lead : leadList){
							Map<String, Object> taskValue = new HashMap<String, Object>();
							taskValue.put("name", lead.get("name"));
							taskValue.put("id", lead.get("id"));
							taskValues.add(taskValue);
						}
					}
					List<Map<String, Object>> opporList = vrtc.getOpporList();
					if(opporList != null && opporList.size() > 0){
						for(Map<String, Object> oppor : opporList){
							Map<String, Object> taskValue = new HashMap<String, Object>();
							taskValue.put("name", oppor.get("name"));
							taskValue.put("id", oppor.get("id"));
							taskValues.add(taskValue);
						}
					}
					card.put("taskvalues", taskValues);
					taskcards.add(card);
				}
			}
		}
	}
	
	/**
	 * 保存拜访计划
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="{id}", method = RequestMethod.POST)
	public Object save(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		
		String objType = paramObj.getString("objtype");
		
		switch(objType) {
			case "CustomerVisit":
				visitSave(paramObj, id);
				break;
			case "NetVisit":
				//TODO 网点拜访保存
				break;
			case "Task":
				//TODO 任务保存
				break;
			default:
				//nothing
		}
				
		return ResponseUtil.getObject();
	}

	/**
	 * 客户拜访保存
	 * @param paramObj
	 * @param id
	 * @throws CrmMessageException
	 */
	private void visitSave(JSONObject paramObj, Long id) throws CrmMessageException {
		VisitsVO visit = new VisitsVO();
		
		String dateStr = paramObj.getString("date");
		Date date = transformDateFromStr(dateStr, "yyyy-MM-dd");
		visit.setDate(date);
		
		long cumId = Long.parseLong(paramObj.getString("accountid"));
		visit.setCumId(cumId);
		
		String contactId = getContactIdStr(paramObj);
		visit.setContactId(contactId);
		
		String bizoppId = paramObj.getString("bizoppid");
		if (bizoppId.equals("")) {
			visit.setOpportunityId((long)0);
		} else {
			visit.setOpportunityId(Long.parseLong(bizoppId));
		}
		
		String purpose = paramObj.getString("purpose");
		visit.setPurpose(purpose);
		
		String validMsg = visitInsertValidator(visit);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(validMsg);
		}
		
		if (id == 0) {
			visit = visitService.insert(visit);
		} else {
			visit.setId(id);
			visit = visitService.update(visit);
		}
		if (visit.getId() == null) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "获取自增主键为空");
		}
	}
	
	/**
	 * 获取联系人Id
	 * @param paramObj
	 * @return
	 */
	private String getContactIdStr(JSONObject paramObj) {
		String contactId = "";
		List<String> contactList = JSONArray.toList(JSONArray.fromObject(paramObj.get("contactid")), new String(), new JsonConfig());
		if (contactList.size() > 0) {
			for (int i = 0; i < contactList.size(); i++) {
				String contact = contactList.get(i);
				if (i == 0){
					contactId = contact;
				} else {
					contactId = contactId + "," + contact;
				}
			}
		}
		return contactId;
	}

	/**
	 * 客户拜访计划新增校验
	 * @param visit
	 * @return String
	 */
	private String visitInsertValidator(VisitsVO visit) {
		
		if (visit == null) {
			return "转换实体失败";
		}
		
		if (visit.getDate() == null) {
        	return  "拜访日期不能为空";
		}
		
		if (visit.getCumId() == 0) {
        	return  "客户不能为空";
		}
		/*
		if (!StringUtils.isNotBlank(visit.getPurpose())) {
        	return  "拜访目的不能为空";
		}
		*/
		
		return "";
	}

	/**
	 * 拜访小结
	 * @param version
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="{id}/summary", method = RequestMethod.PUT)
	public Object summary(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ClientError, "id不能为空");
		}
		
		JSONObject paramObj = RequestUtil.getParamObject(request);

		String objType = paramObj.getString("objtype");

		switch(objType) {
			case "CustomerVisit":
				visitSummary(paramObj, id);
				break;
			case "NetVisit":
				//TODO 网点拜访小结
				break;
			case "Task":
				//TODO 任务小结
				break;
			default:
				//nothing
		}
				
		return ResponseUtil.getObject();
	}
	
	/**
	 * 客户拜访小结校验
	 * @param visit
	 * @return String
	 */
	private String visitUpdateValidator(VisitsVO visit) {
		
		if (!StringUtils.isNotBlank(visit.getSummary())) {
        	return  "拜访总结不能为空";
		}
		
		return "";
	}

	/**
	 * 客户拜访小结
	 * @param paramObj
	 * @param id
	 * @throws CrmMessageException
	 */
	public void  visitSummary(JSONObject paramObj, Long id) throws CrmMessageException {
		VisitsVO visit = new VisitsVO();

		String nextDateStr = paramObj.getString("nextdate");
		Date nextDate = transformDateFromStr(nextDateStr, "yyyy-MM-dd");
		visit.setNextDate(nextDate);
		
		String summary = paramObj.getString("summary");
		visit.setSummary(summary);
		
		String validMsg = visitUpdateValidator(visit);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(validMsg);
		}

		visit.setId(id);
		visit = visitService.summary(visit);
				
		return ;
	}
	
		
	/**
	 * 删除拜访计划
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
	public Object delete(@PathVariable("id") Long id ,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ClientError, "id不能为空");
		}
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String objType = paramObj.getString("objtype");
		
		switch(objType) {
			case "CustomerVisit":
				visitService.delete(id);
				break;
			case "NetVisit":
				//TODO网点拜访删除
				break;
			case "Task":
				//TODO任务删除
				break;
			default:
				//nothing
		}
		
		return ResponseUtil.getObject();
	}
	
	/**
	 * 日程签到
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/locations", method = RequestMethod.POST)
	public Object location(@PathVariable("id") Long id ,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ClientError, "id不能为空");
		}
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String objType = paramObj.getString("objtype");
		
		TraceVO trace = new TraceVO();
		trace.setRelObjId(id);

		//TODO根据参数生成签到实体
		Map<String, String> location = (Map<String, String>)paramObj.get("location");
		trace.setAddress(location.get("address"));
		trace.setLongitude(location.get("longitude"));
		trace.setLatitude(location.get("latitude"));
		trace.setAltitude(location.get("altitude")); 
		
		switch(objType) {
			case "CustomerVisit":
				//设置客户拜访计划的签到类型
				trace.setSignType(13);
				visitService.location(id, trace);
				break;
			case "NetVisit":
				//TODO网点拜访签到
				break;
			case "Task":
				//TODO任务签到
				break;
			default:
				//nothing
		}
		
		return ResponseUtil.getObject();
	}
	
	/**
	 * 拜访签到信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/locations", method = RequestMethod.GET)
	public Object locationInfo(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ServerError, "id不能为空");
		}
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String objType = paramObj.getString("objtype");
		TraceVO traceVO = new TraceVO();
		switch(objType) {
			case "CustomerVisit":
				traceVO = visitLocationInfo(id);
			case "NetVisit":
				//TODO网点拜访详情
				break;
			case "Task":
				//TODO任务详情
				break;
			default:
				//nothing
		}
		
		Map<String, Object> res = new HashMap<String, Object>();
		Map<String, Object> signInfo = new HashMap<String, Object>();
		transTrace(traceVO, signInfo);
		res.put("location", signInfo);
		
		return ResponseUtil.getObject(res);
	}
	
	/**
	 * 转化签到信息
	 * @param trace
	 * @param signInfo
	 */
	private void transTrace(TraceVO trace, Map<String, Object> signInfo) {
		if ((trace.getId() == null) || (trace.getId() == 0)) {
			signInfo.put("latitude", "");
			signInfo.put("longitude", "");
			signInfo.put("address", "");
			//signInfo.put("signintime", "");
		} else {
			signInfo.put("latitude", trace.getLatitude());
			signInfo.put("longitude", trace.getLongitude());
			signInfo.put("address", trace.getAddress());
			//signInfo.put("signintime", trace.getSignTime());
		}
	}

	/**
	 * 客户拜访计划获取签到信息
	 * @param id
	 * @return
	 */
	private TraceVO visitLocationInfo(Long id) {
		VisitsVO visit = visitService.getLocation(id);
		TraceVO trace = new TraceVO();
		if (visit.getTraceId() != null && visit.getTraceId() != 0) {
			trace = visit.getTraceInfo();
		}
		
		return trace;
	}
	
	/**
	 * 拜访计划详情
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/summary", method = RequestMethod.GET)
	public Object summrayInfo(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ServerError, "id不能为空");
		}
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String objType = paramObj.getString("objtype");
		
		switch(objType) {
			case "CustomerVisit":
				return visitSummaryInfo(id);
			case "NetVisit":
				//TODO 网点拜访详情
				break;
			case "Task":
				//TODO 任务详情
				break;
			default:
				//nothing
		}
		
		return ResponseUtil.getObject();
	}
	
	/**
	 * 拜访小结信息
	 * @param id
	 * @return
	 * @throws CrmMessageException 
	 */
	private Object visitSummaryInfo(Long id) throws CrmMessageException {
		VisitsVO visit = visitService.getSummary(id);
		
		Map<String, Object> res = new HashMap<String, Object>();
		Map<String, Object> summary = new HashMap<String, Object>();
		
		summary.put("summary", visit.getSummary());
		summary.put("nextdate", formateDate(visit.getNextDate(), "yyyy-MM-dd"));
		
		res.put("summary", summary);
		
		return ResponseUtil.getObject(res);
	}
	
	/**
	 * 查询日程评论信息
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="comments/{id}", method = RequestMethod.GET)
	public Object getCommentList(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) 
			throws CrmMessageException{
		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ClientError, "id不能为空");
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("visitId", id);
		List<ScheduleCommentVO> commentList = service.getCommentList(paramMap);
		JSONObject result = new JSONObject();
		result.put("data", commentList);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 删除日程评论信息
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="comments/batch", method = RequestMethod.DELETE)
	public Object deleteComment(HttpServletRequest request, HttpServletResponse response) 
			throws CrmMessageException{
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idArray = paramObj.getString("ids");		

		if (idArray == null) {
			throw new CrmMessageException("ids参数为空");
		}
		String[] idStrs = idArray.split(",");
		@SuppressWarnings("unchecked")
		Map<String, Object> searchMap = (Map<String, Object>)paramObj.get("searchMap");
		List<ScheduleCommentVO> commentList = service.deleteCommentByIDs(idStrs, searchMap);
		JSONObject result = new JSONObject();
		result.put("data", commentList);
		return ResponseUtil.getObject(result, PCCodeConstant.Success,"数据删除成功");
		
	}
	
	/**
	 * 查询日程点赞信息 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="goodjobs/{id}", method = RequestMethod.GET)
	public Object getGoodjobList(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) 
		throws CrmMessageException{
		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ClientError, "id不能为空");
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("visitId", id);
		List<ScheduleGoodjobVO> commentList = service.getGoodjobList(paramMap);
		JSONObject result = new JSONObject();
		result.put("data", commentList);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 取消日程点赞信息
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="goodjobs/batch", method = RequestMethod.DELETE)
	public Object deleteGoodjob(HttpServletRequest request, HttpServletResponse response) 
			throws CrmMessageException{
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idArray = paramObj.getString("ids");		

		if (idArray == null) {
			throw new CrmMessageException("ids参数为空");
		}
		String[] idStrs = idArray.split(",");
		@SuppressWarnings("unchecked")
		Map<String, Object> searchMap = (Map<String, Object>)paramObj.get("searchMap");
		List<ScheduleGoodjobVO> goodjobList = service.deleteGoodjobByIDs(idStrs, searchMap);
		JSONObject result = new JSONObject();
		result.put("data", goodjobList);
		return ResponseUtil.getObject(result, PCCodeConstant.Success,"数据删除成功");
		
	}
	
	/**
	 * 获取日程任务卡已录信息列表
	 * @param version
	 * @param id
	 * @param request
	 * @param response
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="{id}/taskinfolist", method = RequestMethod.GET)
	public Object getTaskcardDetail(@PathVariable("version") String version, @PathVariable("id") Long id,
			HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String scheduleType = getScheduleType(paramObj); //日程类型
		Long objType = getObjType(paramObj); //关联业务类型
		Long objBiztype = getObjBiztype(paramObj); //关联业务子类型
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		resultList = service.getCumVisitFinishedList(id,objType,objBiztype,scheduleType);
		
		Map<String, Object> res = new HashMap<String, Object>();
		List<Map<String, Object>> objectList = new ArrayList<Map<String,Object>>();
		for(Map<String, Object> map : resultList){
			Map<String, Object> object = new HashMap<String, Object>();
			List<String> fieldList = new ArrayList<String>();
			fieldList.add(map.get("name").toString());
			object.put("name", fieldList);
			object.put("id", map.get("id"));
			objectList.add(object);
		}
		res.put("taskinfos", objectList);
		return ResponseUtil.getObject(res);
	}
	
	/**
	 * 日程类型
	 * @param paramObj
	 * @return
	 */
	private String getScheduleType(JSONObject paramObj) {
		String scheduleType = paramObj.getString("objtype");
		if(scheduleType.equals(ScheduleTypeEnum.CUSVISIT.getName())){
			scheduleType = String.valueOf(ScheduleTypeEnum.CUSVISIT.getValue());
		}else if(scheduleType.equals(ScheduleTypeEnum.NETVISIT.getName())){
			scheduleType = String.valueOf(ScheduleTypeEnum.NETVISIT.getValue());
		}else if(scheduleType.equals(ScheduleTypeEnum.TASK.getName())){
			scheduleType = String.valueOf(ScheduleTypeEnum.TASK.getValue());
		}
		return scheduleType;
	}

	/**
	 * 关联业务类型
	 * @param paramObj
	 * @return
	 */
	private Long getObjType(JSONObject paramObj) {
		Long objType = 0l;
		String objTypeStr = paramObj.getString("cardtype");
		if(objTypeStr.equals(MtObjTypeEnum.CONTACT.getName())){
			objType = MtObjTypeEnum.CONTACT.getValue();
		}else if(objTypeStr.equals(MtObjTypeEnum.LEAD.getName())){
			objType = MtObjTypeEnum.LEAD.getValue();
		}else if(objTypeStr.equals(MtObjTypeEnum.OPPORTUNITY.getName())){
			objType = MtObjTypeEnum.OPPORTUNITY.getValue();
		}else if(objTypeStr.equals(MtObjTypeEnum.COMPETITIVE.getName())){
			objType = MtObjTypeEnum.COMPETITIVE.getValue();
		}
		return objType;
	}
	
	/**
	 * 关联业务子类型
	 * @param paramObj
	 * @return
	 */
	private Long getObjBiztype(JSONObject paramObj) {
		Long objBiztype = 0L;
		String objBiztypeStr = paramObj.getString("subbnstype");
		if(objBiztypeStr.equals(BiztypeEnum.CONBIZTYPE_1.getName())){
			objBiztype = BiztypeEnum.CONBIZTYPE_1.getValue();
		}else if(objBiztypeStr.equals(BiztypeEnum.LEADBIZTYPE_1.getName())){
			objBiztype = BiztypeEnum.LEADBIZTYPE_1.getValue();
		}else if(objBiztypeStr.equals(BiztypeEnum.OPPOBIZTYPE_1.getName())){
			objBiztype = BiztypeEnum.OPPOBIZTYPE_1.getValue();
		}else if(objBiztypeStr.equals(BiztypeEnum.OPPOBIZTYPE_2.getName())){
			objBiztype = BiztypeEnum.OPPOBIZTYPE_2.getValue();
		}else if(objBiztypeStr.equals(BiztypeEnum.COMPBIZTYPE_1.getName())){
			objBiztype = BiztypeEnum.COMPBIZTYPE_1.getValue();
		}
		return objBiztype;
	}

}
